package rejjie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.core.Local;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import rejjie.common.R;
import rejjie.entity.Employee;
import rejjie.service.EmployeeService;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee){
        //1、将页面提交的密码password进行md5加密处理
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //2、根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<Employee> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.like(Strings.isNotEmpty(employee.getUsername()),Employee::getUsername,employee.getUsername());
        Employee emp = employeeService.getOne(lambdaQueryWrapper);
        //3、如果没有查询到则返回登录失败结果
        if(emp==null){
            return R.error("登录失败");
        }
        //4、密码比对，如果不一致则返回登录失败结果
        if(!emp.getPassword().equals(password)){
            return R.error("登录失败");
        }
        //5、查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if(emp.getStatus()==0){
            return R.error("员工被封禁");
        }
        //6、登录成功，将员工id存入Session并返回登录成功结果
        request.getSession().setAttribute("employee",emp.getId());
        return R.success(emp);
    }


//    http://localhost:8080/employee/logout
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        //清理Session中保存的当前登录员工的id
        request.removeAttribute("employee");
        //返回退出成功的信息
        return R.success("登出系统成功");
    }

    /**
     *
     * @param request
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> save(HttpServletRequest request,@RequestBody Employee employee){
        log.info("新增员工，员工信息：{}",employee.toString());

        //设置初始密码123456，需要进行md5加密处理

        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
        long employeeid = (long)request.getSession().getAttribute("employee");
//        employee.setCreateUser(employeeid);
//        employee.setUpdateUser(employeeid);

        //获得当前登录用户的id
        employeeService.save(employee);
        return R.success("新增员工成功");
    }

    /**
     * 执行分页查询
     * 前端把数据没有按照json的格式进行发送，如果按照json的格式发送，我们接收时，使用@requestBody
     * 按照拼接的方式 用的是@requestParam
     * @param page
     * @param pageSize
     * @param name
     * @return
     *
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name){
        log.info("page = {},pageSize = {},name = {}" ,page,pageSize,name);

        //构造分页构造器
        Page pageinfo = new Page(page, pageSize);

        //构造条件构造器
        //添加过滤条件
        //添加排序条件
        LambdaQueryWrapper<Employee> employeeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        employeeLambdaQueryWrapper.like(Strings.isNotBlank(name),Employee::getName,name);
        employeeLambdaQueryWrapper.orderByAsc(Employee::getUpdateTime);


        //执行查询
        employeeService.page(pageinfo,employeeLambdaQueryWrapper);
        return R.success(pageinfo);

    }

    /**
     * 既可以用来实现员工的禁用和启用功能，也可以完成更新用户的功能
     * @param request
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> update(HttpServletRequest request,@RequestBody Employee employee){
        log.info("接受的用户",employee);
        long employeeid = (long)request.getSession().getAttribute("employee");
//        employee.setUpdateUser(employeeid);
//        employee.setUpdateTime(LocalDateTime.now());
        employeeService.updateById(employee);
        return R.success("员工信息更新成功");
    }

    /**
     * 根据id查找用户信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        log.info("根据id查找用户信息");
        Employee emp = employeeService.getById(id);
        if(emp!=null){
            return R.success(emp);
        }
        return R.error("查找失败");
    }
}
